package com.xk857.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xk857.entities.Forum;
import com.xk857.entities.Label;
import com.xk857.feign.IFeignArticleController;
import com.xk857.feign.req.UserInfoREQ;
import com.xk857.forum.mapper.ForumMapper;
import com.xk857.forum.req.ForumUserREQ;
import com.xk857.forum.service.IForumService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xk857.util.base.BaseRequest;
import com.xk857.util.base.NoResult;
import com.xk857.util.base.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 星空小屋-论坛话题表 服务实现类
 *
 * @author CV大魔王
 * @since 2021-02-23
 */
@Service
public class ForumServiceImpl extends ServiceImpl<ForumMapper, Forum> implements IForumService {

    @Autowired
    private IFeignArticleController feignArticleController;


    @Override
    public IPage<Forum> findHotList(BaseRequest<Forum> req) {
        QueryWrapper<Forum> wrapper = new QueryWrapper<>();
        // 状态为 1 和 2 非删除话题
        wrapper.in("status", Arrays.asList(1, 2));
        // 按回复数降序排列，
        wrapper.orderByDesc("reply");
        return baseMapper.selectPage(req.getPage(), wrapper);
    }

    @Override
    public IPage<Forum> findNewList(BaseRequest<Forum> req) {
        QueryWrapper<Forum> wrapper = new QueryWrapper<>();
        // 状态为 1 和 2 非删除话题
        wrapper.in("status", Arrays.asList(1, 2));
        // 按回复数降序排列，
        wrapper.orderByDesc("update_date");
        return baseMapper.selectPage(req.getPage(), wrapper);
    }

    @Override
    public IPage<Forum> findWaitList(BaseRequest<Forum> req) {
        QueryWrapper<Forum> wrapper = new QueryWrapper<>();
        // 状态为 1 和 2 非删除话题
        wrapper.in("status", Arrays.asList(1, 2));
        // 查询回复数为0，按话题创建时间降序排列，
        wrapper.eq("reply", 0);
        wrapper.orderByDesc("create_date");
        return baseMapper.selectPage(req.getPage(), wrapper);
    }

    @Override
    public IPage<Forum> findListByLabelId(BaseRequest<Forum> req, String labelId) {
        if (StringUtils.isEmpty(labelId)) {
            return null;
        }
        return baseMapper.findListByLabelId(req.getPage(), labelId);
    }

    @Override
    public Forum findById(String id) {
        // 1. 查询话题详情与标签ids
        Forum forum = baseMapper.findForumAndLabelIdsById(id);
        if (forum == null) {
            return null;
        }
        if (CollectionUtils.isNotEmpty(forum.getLabelIds())) {
            List<Label> labelList = feignArticleController.getLabelListByIds(forum.getLabelIds());
            forum.setLabelList(labelList);
        }
        return forum;
    }


    @Override
    public Result updateViewCount(String id) {
        if (StringUtils.isBlank(id)) {
            return Result.error("无效操作");
        }
        Forum forum = baseMapper.selectById(id);
        if (forum == null) {
            return Result.error("话题不存在");
        }
        forum.setViewCount(forum.getViewCount() + 1);
        // 不用设置更新时间，更新时间是编辑后才设置
        baseMapper.updateById(forum);
        return Result.ok();
    }


    @Override
    public String updateOrSave(Forum forum) {
        // 1. id 不为空，是更新操作
        if (StringUtils.isNotEmpty(forum.getId())) {
            // 更新：先删除话题标签中间表数据，再新增到中间表
            baseMapper.deleteForumLabel(forum.getId());
            // 设置更新时间
            forum.setUpdateDate(new Date());
        }
        // 2. 更新或保存到文章信息表（不能放到最后，因为新增后，要返回新增id到forum.id里）
        super.saveOrUpdate(forum);
        // 3. 新增到文章标签中间表
        if (CollectionUtils.isNotEmpty(forum.getLabelIds())) {
            baseMapper.saveForumLabel(forum.getId(), forum.getLabelIds());
        }
        // 响应当前操作的 话题id
        return forum.getId();
    }


    @Override
    public void deleteById(String id) {
        this.updateStatus(id, 0); // 0 已删除
    }


    @Override
    public Result updateThumhup(String id, int count) {
        if (count != -1 && count != 1) {
            return Result.error("无效操作");
        }
        if (StringUtils.isBlank(id)) {
            return Result.error("无效操作");
        }
        Forum forum = baseMapper.selectById(id);
        if (forum == null) {
            return Result.error("话题不存在");
        }
        if (forum.getThumhup() <= 0 && count == -1) {
            return Result.error("无效操作");
        }
        forum.setThumhup(forum.getThumhup() + count);
        // 不用设置更新时间，更新时间是编辑后才设置
        baseMapper.updateById(forum);
        return Result.ok();
    }

    @Override
    public IPage<Forum> findListByUserId(ForumUserREQ req) {
        if (StringUtils.isEmpty(req.getUserId())) {
            return null;
        }
        QueryWrapper<Forum> wrapper = new QueryWrapper<>();
        wrapper.in("status", Arrays.asList(1, 2));
        // 根据用户id查询
        wrapper.eq("user_id", req.getUserId());
        // 排序
        wrapper.orderByDesc("update_date");
        return baseMapper.selectPage(req.getPage(), wrapper);
    }

    @Override
    public Integer getForumTotal() {
        // 查询总话题数
        QueryWrapper<Forum> wrapper = new QueryWrapper<>();
        wrapper.in( "status", Arrays.asList(1, 2) );
        return baseMapper.selectCount(wrapper);
    }

    @Override
    public boolean updateUserInfo(UserInfoREQ req) {
        return baseMapper.updateUserInfo(req);
    }

    @Override
    public Integer searchCountDayNum() {
        return baseMapper.searchCountDayNum();
    }

    @Override
    public Integer searchNumberOfArticlesInYesterdaySDay() {
        return baseMapper.searchNumberOfArticlesInYesterdaySDay();
    }

    @Override
    public Integer searchNumberOfArticlesInWeek() {
        return baseMapper.searchNumberOfArticlesInWeek();
    }


    /**
     * 修改状态
     *
     * @param id     话题id
     * @param status 话题状态
     */
    public void updateStatus(String id, Integer status) {
        Forum forum = baseMapper.selectById(id);
        forum.setStatus(status);
        forum.setUpdateDate(new Date());
        baseMapper.updateById(forum);
    }

}
